/*
 * (c) Copyright 2014 Hewlett-Packard Development Company, L.P. All rights reserved.
 */
package com.hp.snap.gr.cmd;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.management.InstanceNotFoundException;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.snap.gr.utils.Constants;
import com.hp.snap.gr.utils.eium.JMXClientUtils;

/**
 * @since 3.2
 * @author Yang, Lin
 * 
 */
public class SetSiteBizServiceStatusCMD {
    private static Logger logger = LoggerFactory.getLogger(SetSiteBizServiceStatusCMD.class);

    /**
     * <b>input</b>
     * <p>
     * args[0] - args[n-2]: session server list
     * 
     * <pre>
     * LB/snapgr02/lb_moon82 STUDIO/snapgr02/SNAPStudio
     * </pre>
     * 
     * args[n-1]: biz service status
     * 
     * <pre>
     * optional values: Starting, Standby, Running
     * </pre>
     * 
     * <b>output</b>
     * 
     * <pre>
     * {"result":[{"session_server":"LB\/snapgr02\/lb_moon82","state":"Stopped"},{"session_server":"STUDIO\/snapgr02\/SNAPStudio","state":"Running","server_status":"ACTIVE","biz_service_status":"Standby"}]}
     * </pre>
     * 
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) {
        if (logger.isTraceEnabled()) {
            logger.trace(Arrays.toString(args));
        }

        try {
            main0(args);
        } catch (Exception e) {
            if (logger.isTraceEnabled()) {
                logger.trace("Setting site biz service status is failed!", e);
            }
            Constants.CONSOLE
                    .info("Usage: com.hp.snap.gr.cmd.SetSiteBizServiceStatusCMD <session server> <session server> <biz service status>");
            Constants.CONSOLE
                    .info("Example: com.hp.snap.gr.cmd.SetSiteBizServiceStatusCMD STUDIO/snapgr01/SNAPStudio1 OCS/snapgr02/ocs_moon82 Standby");
            System.exit(1);
        } finally {
            try {
                JMXClientUtils.destroy();
            } catch (Exception e) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Destroying JMX connection is failed!", e);
                }
            }
        }
    }

    private static void main0(String[] args) throws Exception {
        int length = args.length;

        String bizServiceStatus = args[length - 1];

        JSONObject json = new JSONObject();
        List<JSONObject> result = new ArrayList<JSONObject>(length - 1);

        for (int ii = 0, nn = length - 1; ii < nn; ii++) {
            String sessionServer = args[ii];
            String[] ss = StringUtils.split(sessionServer, "/");
            String ssHost = ss[1];
            String ssName = ss[2];

            JSONObject jsonSS = new JSONObject();
            jsonSS.put("session_server", sessionServer);

            String state = null;
            String server_status = null;
            String biz_service_status = null;
            try {
                // server_status
                server_status = String.valueOf(JMXClientUtils.getAttribute(ssHost + "/" + ssName
                        + "/ATOM:type=Server,name=ATOM Server", "Status"));

                JMXClientUtils.invokeOperation(ssHost + "/" + ssName + "/" + Constants.JMX_SNAP_OBJECT,
                        Constants.JMX_SET_BIZ_STATUS, new Object[] { bizServiceStatus },
                        new String[] { bizServiceStatus.getClass().getName() });
                biz_service_status = bizServiceStatus;

                state = "Running";

            } catch (InstanceNotFoundException e) {
                state = "Stopped";

            } catch (Exception e) {
                logger.error("invoke setting status operation failed!!, Object Name:{}, operation:{}, param:{} ",
                        new Object[] { ssHost + "/" + ssName + "/" + Constants.JMX_SNAP_OBJECT,
                                Constants.JMX_SET_BIZ_STATUS, bizServiceStatus });
                logger.error("invoke setting failed,{}",e.toString());
                state = "Running";
                biz_service_status = "IDLE";
            }

            jsonSS.put("state", state);
            if (null != server_status) {
                jsonSS.put("server_status", server_status);
            }
            if (null != biz_service_status) {
                jsonSS.put("biz_service_status", bizServiceStatus);
            }

            if (logger.isTraceEnabled()) {
                logger.trace(jsonSS.toString());
            }
            result.add(jsonSS);
        }

        json.put("result", result);

        // output
        Constants.CONSOLE.info(json.toString());
    }
}
